package com.ad_hccm.controller.Appendix;

import com.ad_hccm.controller.Code;
import com.ad_hccm.controller.Result;
import com.ad_hccm.domain.Appendix.SAE;
import com.ad_hccm.domain.User;
import com.ad_hccm.exception.BusinessException;
import com.ad_hccm.interceptor.TokenUtil;
import com.ad_hccm.service.Appendix.SAEService;
import com.ad_hccm.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * TODO 严重不良事件(SAE)报告表
 */
@RestController
@RequestMapping("/sae")
public class SAEController {
    @Autowired
    private SAEService service;
    @Autowired
    TokenUtil tokenUtil;
    @Autowired
    private UserService userService;

    @PostMapping
    public Result save(@RequestBody SAE domain){
        boolean flag = service.save(domain);
        String msg = flag ? "添加失败" : "添加成功" ;
        return new Result( flag ? Code.SAVE_OK : Code.SAVE_ERR, flag, msg);
    }

    @PutMapping
    public Result update(@RequestBody SAE domain) {
        boolean flag = service.update(domain);
        String msg = flag ? "修改成功" : "数据修改失败，请重试";
        return new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERR , flag , msg);
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable String id) {
        if(id.length()!=18) throw new BusinessException(Code.GET_ERR, "请输入18位的身份证");
        List<SAE> domain = service.getById(id);
        Integer code = domain != null ? Code.GET_OK : Code.GET_ERR;
        String msg = domain != null ? "查询成功" : "没有该信息";
        return new Result(code , domain , msg);
    }

    @GetMapping
    public Result getAll(HttpServletRequest request) {
        String token = request.getHeader("token");
        Map<String,String> map = tokenUtil.parseToken(token);
        String userId = map.get("userId");
        User user = userService.getByAccount(userId);
        List<SAE> list = service.getAll(user.getId());
        Integer code = list != null ? Code.GET_OK : Code.GET_ERR;
        String msg = list != null ? "查询成功" : "数据查询失败，请重试";
        return new Result(code , list , msg);
    }
}
